Page({
  data: {
    psyknoTest:0,
    questions: [],     
    currentIndex: 0,   
    id:0,
    selectedOption: null,
    answers: {},        // 保存所有答案 {questionId: {optionId, score}}
    loading: true,
    topicList: [] // 新增：用于存储题目列表
  },

  onLoad(options) {
    console.log("数据id"+options.id);
    this.setData({
      id:options.id
    })
    console.log('id',this.data.id);
    this.loadQuestions(options.id);
  },

  // 加载题目数据
  loadQuestions(id) {
    console.log("ss"+this.data.psyknoTest);
    wx.showLoading({ title: '加载题目中...' });
    
     const psyknoTest = 1; // 实际ID
     console.log("实际数据"+this.data.psyknoTest);
    wx.request({
      url: `http://localhost:8080/topic/withChooses/${id}`,
      method: 'GET',
      success: (res) => {
        if (res.data && Array.isArray(res.data.data)) {
          // 转换为 questions 结构
          const questions = res.data.data.map(topic => ({
            id: topic.id,
            subject: topic.topicName,
            options: (topic.topicChooses || []).map(opt => ({
              id: opt.id,
              value: opt.chooseContext,
              score: opt.score || 0 // 如果有分数字段
            }))
          }));
          this.setData({
            questions,
            loading: false
          });
          wx.hideLoading(); // 这里关闭加载弹窗
        }
      },
      fail: (err) => {
        wx.hideLoading();
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  handleOptionSelect(e) {
    const selectedId = e.currentTarget.dataset.id;
    const { currentIndex, questions } = this.data;
    const currentQuestion = questions[currentIndex];

    const selectedOption = currentQuestion.options.find(
      opt => opt.id === selectedId
    );

    // 保存答案
    this.setData({
      selectedOption: selectedId,
      [`answers[${currentQuestion.id}]`]: {
        optionId: selectedId,
        score: selectedOption.score
      }
    });

    // 如果不是最后一题，自动切换到下一题
    if (currentIndex < questions.length - 1) {
      setTimeout(() => {
        this.setData({
          currentIndex: currentIndex + 1,
          selectedOption: null, // 清空当前选择
        });
      }, 300); 
    } else {
      this.submitAnswers();
    }
  },

  // 上一题（保持不变）
  prevQuestion() {
    const prevIndex = this.data.currentIndex - 1;
    const prevQuestion = this.data.questions[prevIndex];
    
    this.setData({
      currentIndex: prevIndex,
      selectedOption: this.data.answers[prevQuestion.id]?.optionId || null,
    });
  },

  // 提交答案
  submitAnswers() {
    // wx.showLoading({ title: '提交中...' });
    
    // 计算总分
    const totalScore = Object.values(this.data.answers).reduce(
      (sum, answer) => sum + answer.score, 0
    );
    console.log('总分:', totalScore);

    // 格式化提交数据
    const submitData = this.formatAnswersForSubmit();
    console.log('提交数据:', submitData);

    wx.navigateTo({
       url: `/index/pages/scores/scores?totalScore=${totalScore}&testId=${this.data.id}`,
    })
  },

  // 格式化提交数据（保持不变）
  formatAnswersForSubmit() {
    return Object.entries(this.data.answers).map(([questionId, answer]) => ({
      question_id: questionId,
      option_id: answer.optionId,
      score: answer.score
    }));
  }
 
});